/**
 * Project: apollo-base-dal
 * 
 * File Created at 2016年5月6日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.dal.jdbc.sql;

import java.sql.SQLException;
import java.util.Map;

import com.dx.pf.dal.Logger;
import com.dx.pf.dal.constants.DalConstant;
import com.dx.pf.dal.jdbc.mapper.BeanPropertyAccessBeanMapper;

/**
 * @ClassName: SqlHelperInsert
 * @Description: 插入语句的helper
 * @author wuzhenfang(wzfbj2008@163.com)
 * @date 2016年5月6日 上午10:32:49
 * @version V1.0
 */
public class SqlHelperInsert extends SqlOperator {

	private final static Logger logger = Logger.getLogger(SqlHelperInsert.class);

	/** 插入的字段列表部分 */
	private StringBuilder insertColsql = new StringBuilder(64);
	
	/** 插入的字段值部分 */
	private StringBuilder insertValsql = new StringBuilder(64);
	
	public boolean isSetValue = false;// 是否设置值

	public SqlHelperInsert(SqlHelper sqlHelper, Class<?> clazz) {
		super(sqlHelper, clazz);
		super.sql = new StringBuilder("INSERT INTO ");
	}

	/**
	 * 设置插入属性的实体
	 * @param object
	 * @return
	 * @throws SQLException
	 */
	public SqlHelperInsert setEntity(Object object) throws SQLException {
		BeanPropertyAccessBeanMapper beanMapper = new BeanPropertyAccessBeanMapper(object);
		if (super.pkColName == null || beanMapper.getColumnValueMap().get(super.pkColName) == null) {
			logger.error("实体无主键字段或者主键属性字段为空。");
			throw new SQLException("实体无主键字段或者主键属性字段为空。");
		}
		isSetValue = true;
		putAllexecuteMap(beanMapper.getColumnValueMap());

		String insertColListSql = beanMapper.getiColumnListStr().toString();
		String namedParameterSql = beanMapper.getiNamedParameterListStr().toString();
		insertColsql.append(DalConstant.bracket_l).append(insertColListSql).append(DalConstant.bracket_r);
		insertValsql.append(DalConstant.bracket_l).append(namedParameterSql).append(DalConstant.bracket_r);
		return this;
	}

	@Override
	protected void putAllexecuteMap(Map<String, Object> paramMap) {
		super.executeMap = paramMap;
	}

	@Override
	public SqlHelper builder() {
		if (!isSetValue) {
			logger.error("未设置更新的值。");
			throw new NullPointerException("未设置更新的值。");
		}
		super.sql.append(super.tableName).append(insertColsql).append(DalConstant.sql_value).append(insertValsql);
		logger.debug(super.sql.toString());
		return super.sqlHelper;
	}
}
